import React, { useState, useEffect, useContext  } from 'react';
import { Table, Tag, Button, Popconfirm, message,Space, Pagination, Form, Input, Select,DatePicker, Modal, Row, Col, TreeSelect, Radio,Tree,InputNumber    } from 'antd';
import { DictContext } from '../../../context/context';
import { SearchOutlined , RedoOutlined, PlusOutlined, EditOutlined, DeleteOutlined} from '@ant-design/icons';
import DictTag from '../../../components/DictTag';

import { listPost, addPost, delPost, getPost, updatePost } from "../../../api/system/post";
function Post() {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
    const { useDict} = useContext(DictContext);
    const { sys_normal_disable } = useDict('sys_normal_disable');
    const [single, setSingle] = useState(true);
    const [multiple, setMultiple] = useState(true);
    const [ids, setIds] = useState([]);
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [queryParams, setQueryParams] = useState({
    pageNum: 1,
    pageSize: 10,
    postId: '',
    postCode: '',
    postName: '',
    status: '',
    postSort: '',
  });
  const [searchForm] = Form.useForm();
  const [formAdd] = Form.useForm();
  const [open, setOpen] = useState(false);
  const [title, setTitle] = useState('');
  const columns =[
    {
      title: '岗位编号',
      dataIndex: 'postId',
      key: 'postId',
    },
    {
      title: '岗位编码',
      dataIndex: 'postCode',
      key: 'postCode',
    },
    {
      title: '岗位名称',
      dataIndex: 'postName',
      key: 'postName',
    },
    {
      title: '岗位排序',
      dataIndex: 'postSort',
      key: 'postSort',
    },
    {
      title: '状态', dataIndex: 'status', key: 'status',
      render: (text, record) => <DictTag type="sys_normal_disable" value={text} options={sys_normal_disable} />
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => (
            <Space size="middle">
            <Button type='link' onClick={() => handleUpdate(record)}>修改</Button>
            <Popconfirm
                title="删除确认"
                description={`是否确认删除岗位编号为 ${record.postId} 的数据项？`}
                onConfirm={() => handleDelete(record)}
                onCancel={delCancel}
                okText="确定"
                cancelText="取消"
            >
            <Button type='link'>删除</Button>
            </Popconfirm>
            </Space>
      ),
    }
  ];


  useEffect(() => {
    getPostList();
  }, [queryParams]);

  const onChange = (pagination, filters, sorter) => {
    setQueryParams({
      ...queryParams,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
  };

  

  function getPostList() {
    setLoading(true);
    listPost(queryParams).then(res => {
      setData(res.rows);
      setTotal(res.total);
      setLoading(false);
    });
  }

  const onSelectChange = newSelectedRowKeys => {
    //console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
    setSingle(newSelectedRowKeys.length != 1) ;
    setMultiple(!newSelectedRowKeys.length);
    setIds(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  
  const handleUpdate = (record) => {
    console.log(record);
    formAdd.resetFields();
    const postId = record.postId || ids;
    getPost(postId).then(res => {
      formAdd.setFieldsValue(res.data);
      setOpen(true);
      setTitle('修改岗位');
    })
  }

  const handleDelete = (record) => {
    //console.log(record);
    const postId = record.postId || ids;
    delPost(postId).then(res => {
      message.success('删除成功');
      getPostList();
    })
  }

  const handleAdd = () => {
    //console.log('add');
    formAdd.resetFields();
    setOpen(true);
    setTitle('新增岗位');
  }

  const handleOk = () => {
    if(formAdd.getFieldValue().postId === undefined ){
    addPost(formAdd.getFieldValue()).then(res => {
      message.success('新增成功');
      setOpen(false);
      getPostList();
    })
    }else{
    updatePost(formAdd.getFieldValue()).then(res => {
        message.success('修改成功');
        setOpen(false);
        getPostList();
    })
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const delCancel = () => {
    //message.error('取消删除');
  }

  return (
    <div>
        <Row gutter={[16,16]}>
          <Col span={24}>
            <Form form={searchForm} layout="inline">
              <Form.Item label="岗位名称" name="postName">
                <Input placeholder="请输入岗位名称" />
              </Form.Item>
              <Form.Item label="状态" name="status" style={{width: '10%'}}>
                <Select placeholder="请选择状态" options={sys_normal_disable.value} allowClear >
                </Select>
              </Form.Item>
              <Form.Item>
                <Space>
                <Button type="primary" icon={<SearchOutlined />} onClick={() =>
                  setQueryParams({
                    ...queryParams,
                    pageNum: 1,
                    ...searchForm.getFieldsValue(),
                  })
                }>搜索</Button>
                <Button icon={<RedoOutlined />} onClick={() => searchForm.resetFields()}>重置</Button>
                </Space>
              </Form.Item>
            </Form>
          </Col>
          <Col span={24}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>新增</Button>
            <Button icon={<EditOutlined />} onClick={ handleUpdate} disabled={single}>修改</Button>
            <Button icon={<DeleteOutlined />} onClick={handleDelete } disabled={multiple}>删除</Button>
            </Space>
          </Col>
        </Row>
        <Table loading={loading} rowSelection={rowSelection} dataSource={data} columns={columns} pagination={{ pageSize: queryParams.pageSize, current: queryParams.pageNum ,showQuickJumper: true, pageSizeOptions: [3, 5, 10, 20], showSizeChanger: true, total: total, showTotal: total => `共 ${total} 条`}} rowKey={record => record.postId} onChange={onChange}/>
            <Modal open={open} onOk={handleOk} onCancel={handleCancel} title={title} width={600}>
            <Form form={formAdd} layout="inline" style={{marginTop: '20px'}}>
            <Row gutter={[16,16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
              <Form.Item label="岗位名称" name="postName">
                <Input placeholder="请输入岗位名称" />
              </Form.Item>
              </Col>
              </Row>

              <Row gutter={[16,16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
              <Form.Item label="岗位编码" name="postCode">
                <Input placeholder="请输入岗位编码" />
              </Form.Item>
              </Col>
              </Row>

              <Row gutter={[16,16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
              <Form.Item label="岗位排序" name="postSort">
                <InputNumber min={0} max={9999} placeholder="请输入岗位排序" />
              </Form.Item>
              </Col>
              </Row>

              <Row gutter={[16,16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
              <Form.Item label="状态" name="status">
                <Radio.Group>
                  <Radio value="0">正常</Radio>
                  <Radio value="1">停用</Radio>
                </Radio.Group>
              </Form.Item>
              </Col>
              </Row>

              <Row gutter={[16,16]} style={{marginBottom: '20px', width: '100%'}}>
                <Col span={24}>
              <Form.Item label="备注" name="remark">
                <Input.TextArea placeholder="请输入备注" />
              </Form.Item>
              </Col>
            </Row>
            </Form>

            </Modal>
    </div>
  );
}

export default Post;